package cn.hiapi.core.utils;


import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author AdinZ
 * @date 2021/2/21 10:11
 */

public class RegexUtils {

    /**
     * 验证手机号是否正确
     *
     * @param mobile
     * @return
     */
    public static boolean regexMobile(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return false;
        }
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(16[0-9])|(17[013678])|(18[0-9])|(19[0-9]))\\d{8}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    /**
     * 验证邮箱合法性
     *
     * @param mail
     * @return
     */
    public static boolean regexEmail(String mail) {
        if (StringUtils.isEmpty(mail)) {
            return false;
        }
        return Pattern.compile("([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4})").matcher(mail).matches();
    }

    public static String hiddenStr(String str, int start, int end) {
        return RegExUtils.replaceAll(str, "(^.{" + start + "})(.+)(.{" + end + "}$)", "$1***$3");
    }

    public static String hiddenStr(String str, int start) {
        return RegExUtils.replaceAll(str, "(^.{" + start + "})(.+)", "$1" + StringUtils.rightPad("*", str.length() - start, "*"));
    }


    /**
     * 隐藏姓名
     *
     * @param name
     * @return
     */
    public static String hiddenRealname(String name) {
        if (StringUtils.isEmpty(name) || StringUtils.length(name) <= 1) {
            return (name == null ? "" : name) + "**";
        }
        if (StringUtils.length(name) == 2) {
            return RegexUtils.hiddenStr(name, 1);
        }
        return RegexUtils.hiddenStr(name, 1, 1);
    }


    /**
     * 隐藏卡号
     *
     * @param idCard
     * @return
     */
    public static String hiddenIdCard(String idCard) {
        if (StringUtils.isEmpty(idCard) || StringUtils.length(idCard) <= 1) {
            return idCard;
        }
        if (StringUtils.length(idCard) <= 8) {
            return RegexUtils.hiddenStr(idCard, 4);
        }

        if (StringUtils.length(idCard) <= 10) {
            return RegexUtils.hiddenStr(idCard, 4, 2);
        }

        if (StringUtils.length(idCard) <= 12) {
            return RegexUtils.hiddenStr(idCard, 4, 4);
        }

        return RegexUtils.hiddenStr(idCard, 6, 4);
    }


}
